package com.abby.file;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileOperationDemo {
    private static final String DIR_PATH="D:\\cuda";
    private static final String BIG_FILE="G:\\DataSet\\data_train.txt";

    public static void main(String[] args) {
        File dir = new File(DIR_PATH);
        traversalDirsAndFiles(dir);
        readBigFile(BIG_FILE);
        writeBigFile();
    }

    /**
     * traversal the directory include the subdirectories
     * 遍历目录下的文件，包含子目录
     * @param dir, the given directory,给定的目录
     */
    public static void traversalDirsAndFiles(File dir){
        if (!dir.exists()){
            System.out.println("目录不存在！");
            return;
        }
        if(!dir.isDirectory()){
            System.out.println("给定的路径不是目录！");
            return;
        }

        File[] files=dir.listFiles();
        if(files!=null&&files.length>0){
            for (File f:files){
                if(f.isDirectory()){
                    traversalDirsAndFiles(f);
                }else{
                    System.out.println(f);
                }
            }
        }
    }

    /**
     * read a big file
     * 读取大文件
     * @param path,path of the file,文件路径
     */
    private static void readBigFile(String path){
        try {
            InputStream fileInputStream=new FileInputStream(new File(path));
            BufferedInputStream bis = new BufferedInputStream(fileInputStream);
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(bis, StandardCharsets.UTF_8),10*1024*1024);
            String line;
            while ((line=bufferedReader.readLine())!=null){
               System.out.println(line);
            }
            fileInputStream.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * write a big file
     * 写一个大文件
     */
    private static void writeBigFile(){
        try {
            File f=new File("G:\\big.txt");
            if(!f.exists()){
                f.createNewFile();
            }
            OutputStream outputStream=new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(bos,StandardCharsets.UTF_8),10*1024*1024);
            for(int i=0;i<100000;i++){
                bufferedWriter.write(String.format("this is the line %d \n",i));
                bufferedWriter.flush();
            }
            outputStream.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
